﻿using System;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using Microsoft.TeamFoundation.Common;
using Microsoft.TeamFoundation.Framework.Server;
using Microsoft.TeamFoundation.VersionControl.Server;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Microsoft.TeamFoundation.Client;
using System.Configuration;
using System.Text.RegularExpressions;
using CodePlex.TfsPluginSuite.Configuration;

namespace CodePlex.TfsPluginSuite
{
    public class ForbiddenPatternsPolicy : ISubscriber
    {
        public string Name
        {
            get { return "CodePlex.TfsPluginSuite.ForbiddenPatternsPolicy"; }
        }

        public SubscriberPriority Priority
        {
            get { return SubscriberPriority.Normal; }
        }

        public Type[] SubscribedTypes()
        {
            return new Type[1] { typeof(CheckinNotification) };
        }

        public EventNotificationStatus ProcessEvent(TeamFoundationRequestContext requestContext,
            NotificationType notificationType,
            object notificationEventArgs,
            out int statusCode,
            out string statusMessage,
            out ExceptionPropertyCollection properties)
        {

            EventNotificationStatus response = EventNotificationStatus.ActionPermitted;
            properties = new ExceptionPropertyCollection();
            statusMessage = String.Empty;
            statusCode = 0;


            var config = TfsPluginSuiteConfigurationManager.Section.ForbiddenPatternsPolicy;

            if (!config.Enabled)
            {
                return response;
            }


            // If this is a check-in notification and is a decision point
            if (notificationEventArgs is CheckinNotification && notificationType == NotificationType.DecisionPoint)
            {
                CheckinNotification args = notificationEventArgs as CheckinNotification;
                

                foreach (ForbiddenPatternConfigurationElement forbiddenPatternConfigurationElement in config)
                {
                    foreach (string path in args.GetSubmittedItems(requestContext))
                    {
                        if (Regex.IsMatch(path, forbiddenPatternConfigurationElement.RegularExpression))
                        {
                            statusMessage = forbiddenPatternConfigurationElement.Message;
                            response = EventNotificationStatus.ActionDenied;
                        }
                    }
                }

            }
            return response;
        }
    }
}

